// 引入获取临时id工具
import getUserTempId from "@/utils/userTempId"
import { SET_USER_TOKEN, SET_USERINFO, RESET_USER_INFO } from "../constant-type"
import { req } from "@/api"
import { getToken, setToken, removeToken } from "@/utils/token"
const state = {
    // 用户临时id
    userTempId: getUserTempId(),
    token: getToken() || '',
    userInfo: {}
}
const mutations = {
    // 设置token
    [SET_USER_TOKEN](state, payload) {
        state.token = payload.token
        // 数据持久化token
        setToken(payload.token)
    },
    // 设置用户信息
    [SET_USERINFO](state, payload) {
        state.userInfo = payload.userInfo
    },

    // 重置用户信息及token
    [RESET_USER_INFO](state) {
        state.token = ''
        state.userInfo = {}
        removeToken();
    }

}
const actions = {
    // 登录获取token
    async getUserToken({ commit }, userInfo) {
        try {
            const result = await req.login(userInfo)
            commit(SET_USER_TOKEN, { token: result.token })
        } catch (e) {
            // alert(e.message)

            return Promise.reject(e);
        }

    },
    // 获取用户信息
    async getUserInfo({ commit }) {
        try {
            const result = await req.getUserInfo();

            commit(SET_USERINFO, { userInfo: result })
        } catch (e) {


            return Promise.reject(e)
        }
    },
    // 退出登录
    async logOut({ commit }) {
        try {
            await req.logOut();
            commit(RESET_USER_INFO)

        } catch (e) {
            alert(e.message);
        }
    },

}


export default {
    namespaced: true,
    state,
    mutations,
    actions
}